package com.ljd.controller;

import com.ljd.service.MsmService;
import com.ljd.util.R;
import com.ljd.utils.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
//@CrossOrigin
public class MsmController {
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    MsmService msmService;

    @GetMapping("/send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //1 从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        // redis没有获取到进行阿里云发送
        //生成随机值传递到阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        // 调用service发送短信的方法
        Boolean isSend =msmService.sendMsm(code, phone);
        if(isSend){

            redisTemplate.opsForValue().set(phone,code,7, TimeUnit.DAYS);
            return R.ok();
        }else{
            return R.error().message("发送失败");
        }
    }

}
